/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-04-06 13:13:27
 * @LastEditTime: 2022-04-22 14:39:58
 */

import React, { createContext, useContext, useReducer } from 'react';
import { message, Modal } from 'antd';
import { FuncAndNavReducer } from '../reducers/FuncAndNavReducer';
import {
  ADD_TREE_DATA,
  DELETE_TREE_DATA,
  EDIT_TREE_DATA,
  SAVE_REF,
  SET_SELECT_NAV,
  SET_TREE_DATA
} from '../constants';
import {
  createFunctionalRights,
  deleteFunctionalRights,
  editFunctionalRights,
  fetchFunctionalRightsList
} from '@/api/right';
import { SET_SELECTED_ITEM } from '@/view/accession/BatchManage/constants';

const initialState = {
  // 选中的导航条目
  selectItems: [],
  // 导航数据扁平结构
  flatData: [],
  // 导航数据树结构
  treeData: [],
  // 导航详情表单ref
  formRef: {}
};

const FuncAndNavContext = createContext();

const FuncAndNavContextProvider = (props) => {
  const [state, dispatch] = useReducer(FuncAndNavReducer, initialState);

  const actions = {
    /**
     * @description: 设置表格中选中条目的key
     * @param {number[]} selectArr
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取导航树结构
     */
    getTreeData() {
      return new Promise((resolve, reject) => {
        fetchFunctionalRightsList({})
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_TREE_DATA, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 添加功能权限
     * @param {*} params 添加功能权限的信息
     */
    createNavItem(params) {
      return new Promise((resolve, reject) => {
        createFunctionalRights(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_TREE_DATA, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 添加功能权限
     * @param {*} params 添加功能权限的信息
     */
    editNavItem(params) {
      return new Promise((resolve, reject) => {
        editFunctionalRights(params)
          .then((res) => {
            const { data } = res;
            message.success('编辑成功');
            dispatch({ type: EDIT_TREE_DATA, data, id: data.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 保存导航信息表单ref
     * @param {*} formRef 导航信息表单的ref
     * @return {*}
     */
    saveRef(formRef) {
      dispatch({ type: SAVE_REF, data: formRef });
    },

    /**
     * @description: 触发导航信息表单提交
     */
    clickSaveBtn() {
      state.formRef?.current?.submit();
    },

    /**
     * @description: 删除功能权限（导航）
     * @param {number|number[]} id 删除导航的ID
     */
    deleteNavItem(id) {
      Modal.confirm({
        title: '删除',
        content: '确认删除当前导航节点？',
        onOk() {
          deleteFunctionalRights(id).then((res) => {
            const ids = res.data.map((item) => parseInt(item, 10));
            dispatch({ type: DELETE_TREE_DATA, ids });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    setSelectNav(data) {
      dispatch({ type: SET_SELECT_NAV, data });
    }
  };

  return (
    <FuncAndNavContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </FuncAndNavContext.Provider>
  );
};

export const useFuncAndNavContext = () => {
  return useContext(FuncAndNavContext);
};

export { FuncAndNavContext, FuncAndNavContextProvider };
